<?php
namespace model;
use model\DBConnection;
use PDO;
class HomeQuery{
	
	
	public static function insertRoom($name){
		
		if(!self::isRoomNameAvailable($name)){
			throw new \Exception("Room with that name already exists");
		}
		
		$conn = DBConnection::getDBConnection();
		$stmt = "INSERT INTO room (name)
					VALUES (:NAME)";
		
		$query = $conn->prepare($stmt);
		$query->bindValue(":NAME", $name,PDO::PARAM_STR);
		$query->execute();
	}
	
	public static function insertRoomToPlayer($playerId,$name){
		if(self::playerIsInRoom($playerId) != ""){
			throw new \Exception("Player is already in room");
		}
		
		$roomId = self::getRoomId($name);
		
		$conn = DBConnection::getDBConnection();
		$stmt = "UPDATE player
					SET room_id = :ROOM_ID
					WHERE player_id = :PLAYER_ID";
		
		$query = $conn->prepare($stmt);
		$query->bindValue(":PLAYER_ID", $playerId,PDO::PARAM_INT);
		$query->bindValue(":ROOM_ID", $roomId,PDO::PARAM_INT);
		$query->execute();
	}
	
	public static function playerIsInRoom($playerId){
		$conn = DBConnection::getDBConnection();
		$stmt = "SELECT room_id 
				FROM player
				WHERE player_id = :PLAYER_ID";
		
		$query = $conn->prepare($stmt);
		$query->bindValue(":PLAYER_ID", $playerId,PDO::PARAM_INT);
		$query->execute();
		
		$row = $query->fetch();
		
		echo $row['room_id'];
	}
	
	private static function getRoomId($name){
		$conn = DBConnection::getDBConnection();
		$stmt = "SELECT room_id 
				FROM room 
				where name = :NAME ";
		$query = $conn->prepare($stmt);
		$query->bindValue(":NAME", $name,PDO::PARAM_STR);
		$query->execute();
		$ret = $query->fetch();
		
		return $ret['room_id'];
	}
	
	private static function isRoomNameAvailable($name){
		$conn = DBConnection::getDBConnection();
		$stmt = "SELECT room_id
				FROM room
				where name = :NAME ";
		$query = $conn->prepare($stmt);
		$query->bindValue(":NAME", $name,PDO::PARAM_STR);
		$query->execute();
		$ret = $query->fetch();
		
		if($query->rowCount() != 0){
			return false;
		}
		
		return true;
	}
}
	
	

